<template>
  <div class="container">
    <van-pull-refresh class="container" v-model="isLoading" @refresh="onRefresh">

      <div class="logo" @click="goToHome">
        <img src='../../assets/img/gohome.png' />
        TITIKA ACTIVE
        <p>返回首页</p>
        <!-- <img src='../../assets/img/logo-b.jpg' /> -->
      </div>
      <div class="list">
        <div class="tit">请选择支付方式</div>
        <div class="item" @click="check(0)" v-if="browserType==='wechat'">
          <div class="label">
            <img src='../../assets/img/wechat.png' />
            微信支付
          </div>
          <div class="value">
            <i class="check" :class="{checked: checkIndex === 0}"></i>
          </div>
        </div>
        <div class="item" @click="check(1)">
          <div class="label">
            <img src='../../assets/img/alipay.png' />
            支付宝
          </div>
          <div class="value">
            <i class="check" :class="{checked: checkIndex === 1}"></i>
          </div>
        </div>
      </div>
      <!-- <div class="test">{{payment}}</div> -->
    </van-pull-refresh>

    <div class="total">
      <div class="txt">
        <span>实付金额</span>
        <i>¥ {{ payAmout }}</i>
      </div>
      <!-- <div class="btn" :class="btnActive? 'on':''" @click="pay">立即支付</div> -->
      <div class="btn on" @click="pay">立即支付</div>
    </div>
    <van-loading 
      v-if="loadingShow" 
      class="loading" 
      size="24px" 
      vertical
    >
      订单支付中...
    </van-loading>

    <!-- <div class="authwx">
      <div class="authbtn" @click="authWx">微信授权支付</div>
    </div> -->
  </div>
</template>

<script>
import wx                 from 'weixin-js-sdk'
import AdaPay             from '../../assets/js/adaPay.min'
import { Toast }          from 'vant'
import { request }        from "../../utils"

import { getPayment }      from '../../network/pay'
const {
  EVN,
  productionDomain,
  natDomain,
} = require("../../config/global.js")
import { wxAppId } from "../../config/global"
import { getQueryString, filterEmoji, getBrowserType } from '../../utils'
import { getUserOrder, getUserDetail } from '../../network/user'

export default {
  data() {
    return {
      count: 0,
      isLoading: false,
      browserType: '',
      userKey: localStorage.getItem('userKey'),
      payment: null,
      payAmout: null,
      way: null,
      checkIndex: 0,
      orderId: null,
      loadingShow: false,
      btnActive: false,
      order: {}
    }
  },
  async mounted() {
    console.log('pay page')
    // 获取浏览器类型
    this.browserType = getBrowserType()
    
    if(this.browserType === 'wechat'){
      // 检测是否绑定过微信，未绑定无法支付
      this.authWx()
    } else {
      this.checkIndex = 1
    }
    
    // 获取订单id和支付总额
    this.orderId = this.$route.query.orderId
    // this.payAmout = this.$route.query.payAmout
    this.way = this.$route.query.way
    this.getUserOrder()

    // 获取payment
    await this.getPayment()
    this.btnActive = true

    if(this.way === 'toalipay'){
      this.pay()
    }

  },
  methods: {
    onRefresh() {
      this.getUserOrder(async () => {
        Toast('刷新成功')
        this.isLoading = false
        // 获取payment
        await this.getPayment()
        this.btnActive = true
      })
    },
    getUserOrder(cb){
      let requestData = {
        userkey: this.userKey,
        id: this.orderId
      }
      getUserOrder(requestData, order => {
        this.payAmout = order.Order.RealTotalAmount
        cb && cb()
      })
    },
    goToHome(){
      this.$router.push('/best')
    },
    getUserDetail(){
      return new Promise(resolve => {
        let requestData = {
          userKey: this.userKey
        }
        getUserDetail(requestData, info => {
          resolve(info.OpenId !== null)
        })
      })
    },
    async authWx(){
      // 不存在微信信息时
      let hasOpenId = await this.getUserDetail()
      if(!hasOpenId){
        // 根据code获取openid，绑定微信账号
        let code = getQueryString('code')
        if(code){
          request({
            url: "api/Wx/GetUser",
            params: { code },
          }).then((res) => {
            if (res.data.Success) {
              let wxData = res.data.Data
              wxData.nickname = filterEmoji(wxData.nickname) // 去除微信昵称中的表情符号
              localStorage.setItem("wxInfo", JSON.stringify(wxData))

              // 绑定微信账号
              this.bindWechat(wxData)
            } else {
              console.log("获取微信用户信息失败...")
              this.getCode()
            }
          })
        } else {
          this.getCode()
        }
      }
    },
    bindWechat(wxData){
      if(!wxData){
        console.log('请同意微信授权后绑定')
        return false
      }
      
      let requestData = {
        userName: localStorage.getItem('phone'),
        password: localStorage.getItem('phonePassword'),
        oauthType: 'Himall.Plugin.OAuth.WeiXin',
        oauthOpenId: wxData.openid,
        unionid: wxData.unionid,
        headimgurl: wxData.headimgurl,
        oauthNickName: wxData.nickname,
        sex: wxData.sex,
        city: wxData.city,
        province: wxData.province,
      }
      console.log('binding', requestData)
      // return false

      request({
        url: 'api/Login/GetUser',
        params: requestData
      }).then(async res => {
        if(res.data.Data.success){
          console.log('绑定微信号成功')
          // 获取payment
          try {
            await this.getPayment()
            this.btnActive = true
          } catch (error) {
            console.log('catch error: ', error)
          }
        } else {
          localStorage.setItem("wxInfo", null)
          Toast('请绑定微信账号') // res.data.Msg
        }
      })
    },
    getCode(){
      let redirectUrl = location.href
          let restUrl = redirectUrl.substr(redirectUrl.indexOf("#/pay"))
          
          redirectUrl =
            EVN === "development"
              ? `${natDomain}${restUrl}`
              : `${productionDomain}Images/dist/${restUrl}`

          let snsapi =
              "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
              wxAppId +
              "&redirect_uri=" +
              encodeURIComponent(redirectUrl) +
              "&response_type=code&scope=snsapi_userinfo"

          location.href = snsapi
    },
    async check(index){
      this.checkIndex = index

      this.btnActive = false
      this.payment = null
      await this.getPayment()
      this.btnActive = true
    },
    /**
     * 获取支付payment，用于发起支付
     */
    getPayment(){
      return new Promise((resolve, reject) => {
        let requestData = {
          orderIds: this.orderId, // 多个逗号隔开
          typeid: this.checkIndex === 0 ? 'wx':'alipay', // alipay 或 wx
        }
        // console.log(requestData)
        // return false
        getPayment(requestData, res => {
          console.log('payment: ', JSON.stringify(res.data.Data))
          let payment = res.data.Data
          this.payment = payment
          resolve()
        })
      })
    },
    /**
     * 发起微信支付
     */
    pay(){
      console.log('start pay')
      let payment = this.payment
      if(!payment){
        console.log('初始化未完成 或 未获取到支付前相关参数,请查看接口GetPayMent')
        return false
      }

      // 微信浏览器 - 微信支付
      if(this.browserType === 'wechat'){
        // 微信浏览器里选择里微信支付
        if(this.checkIndex === 1){
          let orderId = this.orderId
          let payAmout = this.payAmout
          this.$router.push({
            path: '/toalipay',
            query: {
              orderId,
              payAmout
            }
          })
          return false
        }
        console.log('type: wechat')
        wx.ready(() => {
          this.loadingShow = true
          // 调用三方sdk进行支付
          AdaPay.doPay(payment, (res) => {
            let payRet = JSON.stringify(res)
            console.log(payRet)
            this.loadingShow = false
            Toast(res.result_message)
            setTimeout(() => {
              if(this.$route.query.ordertype === 'v'){
                this.$router.push('userClass')
              } else {
                this.$router.push('orders')
              }
            }, 1000);
          })
        })
      } 
      // 其他浏览器 - 支付宝支付
      else {
        console.log('type: browser')
        // this.loadingShow = true
        // 调用三方sdk进行支付
        AdaPay.doPay(payment, (res) => {
          console.log('payfinished', res)
          if(res.result_status === 'succeeded'){
            // this.loadingShow = false
            Toast(res.result_message)
            setTimeout(() => {
              if(this.$route.query.ordertype === 'v'){
                this.$router.push('userClass')
              } else {
                this.$router.push('orders')
              }
            }, 1000);
          }
        })
      }
    },
  },
}
</script>

<style scoped>
.container{
  height: 100vh;
}
.logo{
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  color: #fff;
  background-color: #000;
  margin-bottom: 10px;
  padding: 0 20px;
}
.logo img{
  width: 22px;
  margin-bottom: 4px;
  margin-right: 3px;
}
.logo p{
  flex-grow: 1;
  text-align: right;
  margin-bottom: 4px;
  font-size: 14px;
}
.list{
  padding-top: 5px;
  padding: 0 20px;
  background: #fff;
}
.list .tit{
  color: #999;
  line-height: 50px;
  background-color: #fff;
  border-bottom: 1px solid #e4e4e4;
}
.list .item{
  color: #333;
  height: 60px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  border-bottom: 1px solid #e4e4e4;
}
.list .item:last-child{
  border-bottom: none;
}
.list .item .label{
  color: #333;
}
.list .item .label img{
  width: 20px;
  margin-right: 6px;
}
.list .item .value .check{
  display: inline-block;
  width: 14px;
  height: 14px;
  border-radius: 50%;
  border: 1px solid #e4e4e4;
}
.list .item .value .checked{
  position: relative;
  border-color: #222;
  background-color: #222;
}
.list .item .value .checked:after{
  display: block;
  content: '';
  position: absolute;
  width: 8px;
  height: 4px;
  left: 3px;
  top: 3px;
  border-radius: 1px;
  transform: rotate(-45deg);
  border-bottom: 2px solid #fff;
  border-left: 2px solid #fff;
}
.total{
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
}
.total .txt{
  flex-grow: 1;
}
.total .txt span{
  padding-left: 20px;
  padding-right: 10px;
  font-size: 14px;
  color: #666;
}
.total .txt i{
  font-size: 18px;
}
.total .btn{
  flex-grow: 0;
  width: 120px;
  height: 60px;
  line-height: 60px;
  color: #fff;
  text-align: center;
  background-color: #ccc;
  border: none;
  box-sizing: border-box;
  margin: 0;
  overflow: hidden;
}
.total .btn.on{
  background-color: #d50721;
}
.loading{
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  background: rgba(0,0,0,.8);
}
.loading .van-loading__text{
  color: rgba(255, 255, 255, .8);
}
.test{
  font-size: 12px;
  color: #999;
}
.authwx{
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(0,0,0,.6);
}
.authbtn{
  width: 200px;
  line-height: 50px;
  color: #fff;
  font-size: 16px;
  text-align: center;
  border-radius: 4px;
  background-color: #21c303;
}
</style>